package com.example.democonfigserver.modules.app;

import com.example.democonfigserver.modules.config.ConfigRepository;
import com.example.democonfigserver.modules.project.Project;
import com.example.democonfigserver.modules.project.ProjectRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import static com.example.democonfigserver.constant.ValidationConstant.ERROR_MESSAGE_PROJECT_ID_NULL;

/**
 * @author wangbin
 */
@RestController
@RequestMapping("/app")
@Validated
public class AppController {
    @Resource
    private AppRepository appRepository;
    @Resource
    private ProjectRepository projectRepository;
    @Resource
    private ConfigRepository configRepository;

    @GetMapping
    public Page<App> pageList(Pageable pageable, @NotNull(message = ERROR_MESSAGE_PROJECT_ID_NULL) Integer projectId) {
        return appRepository.findPageByProjectId(pageable, projectId);
    }

    @GetMapping("/{id}")
    public App getOne(@PathVariable Integer id) {
        return appRepository.findIdFetch(id).orElseThrow(NullPointerException::new);
    }

    @PostMapping
    public void save(@RequestBody @Valid App app, @NotNull(message = ERROR_MESSAGE_PROJECT_ID_NULL) Integer projectId) {
        if (app.getProject() == null) {
            Project project = projectRepository.findById(projectId).orElseThrow(NullPointerException::new);
            app.setProject(project);
        }
        appRepository.save(app);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Integer id) {
        appRepository.deleteById(id);
    }
}
